package com.xm.zhEnHelper.mapper;

import com.xm.zhEnHelper.dto.ColumDTO;
import com.xm.zhEnHelper.dto.FieldValue;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

public interface TableOperateMapper {

    @Select("SELECT table_name FROM information_schema.tables WHERE table_schema = #{schemaName}")
    List<String> queryTableNames(String schemaName);


    @Select("SELECT" +
            "    COLUMN_NAME AS fieldName, " +
            "    COLUMN_TYPE AS fieldType, " +
            "    IS_NULLABLE AS allowNull, " +
            "    COLUMN_KEY AS fieldKey " +
            "FROM " +
            "    INFORMATION_SCHEMA.COLUMNS " +
            "WHERE TABLE_SCHEMA = #{schemaName} AND TABLE_NAME = #{tableName}")
    List<ColumDTO> queryTableColumns(String schemaName,String tableName);


    @Select(
            value = "<script>" +
            "SELECT" +
                    "  <choose>" +
                    "    <when test='columnNames != null and columnNames.size() > 0'>" +
                    "      <foreach collection='columnNames' item='column' separator=','>" +
                    "        ${column}" +
                    "      </foreach>" +
                    "    </when>" +
                    "    <otherwise>*</otherwise>" +
                    "  </choose>" +
                    "FROM ${schemaName}.${tableName}" +
                    "</script>"
    )
    List<Map<String, Object>> queryTableData(String schemaName,String tableName, List<String> columnNames);


    @Update({
            "<script>" +
                    " UPDATE ${schemaName}.${tableName}" +
                    "<set>" +
                    "  <foreach collection='data' item='value' index='key' separator=','>" +
                    "    ${key} = #{value}" +
                    "  </foreach>" +
                    "</set>" +
                    "WHERE ${keyName} = #{keyValue}" +
            "</script>"
    })
    int updateTableData(
            @Param("schemaName") String schemaName,
            @Param("tableName") String tableName,
            @Param("data") Map<String, Object> data,
            @Param("keyName") String keyName,
            @Param("keyValue") Object keyValue);
}
